#!/bin/bash

# Binance SDK Unified Examples 运行脚本
# 使用方法: ./scripts/run_examples.sh [example_name]

set -e

# 获取脚本所在目录的父目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# 切换到项目根目录
cd "$PROJECT_ROOT"

# 打印工作目录信息
echo "脚本目录: $SCRIPT_DIR"
echo "项目根目录: $PROJECT_ROOT"
echo "当前工作目录: $(pwd)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

test_api_key="0eSVh2diyBaOh9tKEcZjCEHkglV3wo2Es2tKTo4z8535rt4ECEK3ULlPVuD5FmbP"
test_secret_key="DpCpq1kpIpjK6gwNGKTOK39gL7Cpd73nxOAQQdUOyBE3MsP2ESt8BjDw4mSET4TS"

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查环境变量
check_env() {
    print_info "检查环境变量..."
    
    if [ -z "$BINANCE_API_KEY" ]; then
        print_warning "BINANCE_API_KEY 未设置，使用默认测试密钥"
        export BINANCE_API_KEY="${test_api_key}"
    fi
    
    if [ -z "$BINANCE_SECRET_KEY" ]; then
        print_warning "BINANCE_SECRET_KEY 未设置，使用默认测试密钥"
        export BINANCE_SECRET_KEY="${test_secret_key}"
    fi
    
    # 设置默认环境变量
    if [ -z "$BINANCE_PRODUCT_TYPE" ]; then
        print_info "设置默认产品类型: Spot"
        export BINANCE_PRODUCT_TYPE="Spot"
    fi
    
    if [ -z "$BINANCE_ENVIRONMENT" ]; then
        print_info "设置默认环境: Demo"
        export BINANCE_ENVIRONMENT="Demo"
    fi
    
    if [ -z "$BINANCE_TIMEOUT_SECONDS" ]; then
        print_info "设置默认超时: 30秒"
        export BINANCE_TIMEOUT_SECONDS="30"
    fi
    
    if [ -z "$BINANCE_RETRY_COUNT" ]; then
        print_info "设置默认重试次数: 3次"
        export BINANCE_RETRY_COUNT="3"
    fi
    
    if [ -z "$RUST_LOG" ]; then
        print_info "设置默认日志级别: info"
        export RUST_LOG="info"
    fi
    
    print_success "环境变量检查完成"
    print_info "当前配置:"
    print_info "  产品类型: $BINANCE_PRODUCT_TYPE"
    print_info "  环境: $BINANCE_ENVIRONMENT"
    print_info "  超时: ${BINANCE_TIMEOUT_SECONDS}秒"
    print_info "  重试次数: ${BINANCE_RETRY_COUNT}次"
    print_info "  日志级别: $RUST_LOG"
}

# 检查依赖
check_dependencies() {
    print_info "检查依赖..."
    
    if ! command -v cargo &> /dev/null; then
        print_error "Cargo 未安装，请先安装 Rust"
        exit 1
    fi
    
    if ! command -v rustc &> /dev/null; then
        print_error "Rust 编译器未安装"
        exit 1
    fi
    
    print_success "依赖检查完成"
}

# 编译项目
build_project() {
    print_info "编译项目..."
    
    if cargo build --examples; then
        print_success "项目编译成功"
    else
        print_error "项目编译失败"
        exit 1
    fi
}

# 运行基础示例
run_basic_example() {
    print_info "运行基础使用示例..."
    
    if cargo run --example basic_usage; then
        print_success "基础示例运行成功"
    else
        print_error "基础示例运行失败"
        exit 1
    fi
}

# 运行WebSocket示例
run_websocket_example() {
    print_info "运行WebSocket示例..."
    
    if cargo run --example websocket_usage; then
        print_success "WebSocket示例运行成功"
    else
        print_error "WebSocket示例运行失败"
        exit 1
    fi
}

# 运行WebSocket多产品测试
run_websocket_multi_product() {
    print_info "运行WebSocket多产品测试..."
    print_info "测试Spot、USDM、CoinM的WebSocket连接"
    print_info "使用Live环境获取真实行情数据"
    
    if cargo run --example websocket_usage; then
        print_success "WebSocket多产品测试运行成功"
    else
        print_error "WebSocket多产品测试运行失败"
        exit 1
    fi
}

# 运行环境变量配置示例
run_env_config_example() {
    print_info "运行环境变量配置示例..."
    
    if cargo run --example env_config; then
        print_success "环境变量配置示例运行成功"
    else
        print_error "环境变量配置示例运行失败"
        exit 1
    fi
}

# 运行多产品类型示例
run_multi_product_example() {
    print_info "运行多产品类型示例..."
    
    if cargo run --example multi_product; then
        print_success "多产品类型示例运行成功"
    else
        print_error "多产品类型示例运行失败"
        exit 1
    fi
}

# 运行公共API示例
run_public_api_example() {
    print_info "运行公共API示例..."
    
    if cargo run --example public_api; then
        print_success "公共API示例运行成功"
    else
        print_error "公共API示例运行失败"
        exit 1
    fi
}

# 运行多产品类型API测试
run_multi_api_test() {
    print_info "运行多产品类型API测试..."
    
    if cargo run --example multi_api_test; then
        print_success "多产品类型API测试运行成功"
    else
        print_error "多产品类型API测试运行失败"
        exit 1
    fi
}

# 运行API兼容性测试
run_api_compatibility_test() {
    print_info "运行API兼容性测试..."
    
    if cargo run --example api_compatibility_test; then
        print_success "API兼容性测试运行成功"
    else
        print_error "API兼容性测试运行失败"
        exit 1
    fi
}

# 运行Demo模式测试
run_demo_mode_test() {
    print_info "运行Demo模式测试..."
    
    if cargo run --example demo_mode_test; then
        print_success "Demo模式测试运行成功"
    else
        print_error "Demo模式测试运行失败"
        exit 1
    fi
}

# 运行Demo模式快速测试
run_demo_quick_test() {
    print_info "运行Demo模式快速测试..."
    
    if cargo run --example demo_quick_test; then
        print_success "Demo模式快速测试运行成功"
    else
        print_error "Demo模式快速测试运行失败"
        exit 1
    fi
}

# 运行日志测试
run_log_test() {
    print_info "运行日志测试..."
    
    if cargo run --example log_test; then
        print_success "日志测试运行成功"
    else
        print_error "日志测试运行失败"
        exit 1
    fi
}

# 运行币本位合约测试
run_coinm_test() {
    print_info "运行币本位合约测试..."
    
    if cargo run --example coinm_test; then
        print_success "币本位合约测试运行成功"
    else
        print_error "币本位合约测试运行失败"
        exit 1
    fi
}

# 运行币本位合约API调试
run_debug_coinm_api() {
    print_info "运行币本位合约API调试..."
    
    if cargo run --example debug_coinm_api; then
        print_success "币本位合约API调试运行成功"
    else
        print_error "币本位合约API调试运行失败"
        exit 1
    fi
}

# 运行币本位合约解析测试
run_test_coinm_parsing() {
    print_info "运行币本位合约解析测试..."
    
    if cargo run --example test_coinm_parsing; then
        print_success "币本位合约解析测试运行成功"
    else
        print_error "币本位合约解析测试运行失败"
        exit 1
    fi
}

# 显示API密钥信息
run_show_api_keys() {
    print_info "显示API密钥信息..."
    
    if cargo run --example show_api_keys; then
        print_success "API密钥信息显示成功"
    else
        print_error "API密钥信息显示失败"
        exit 1
    fi
}

# 运行所有示例
run_all_examples() {
    print_info "运行所有示例..."
    
    run_basic_example
    echo ""
    run_websocket_example
    echo ""
    run_env_config_example
    echo ""
    run_multi_product_example
    echo ""
    run_public_api_example
    echo ""
    run_multi_api_test
    echo ""
    run_api_compatibility_test
    echo ""
    run_demo_mode_test
    echo ""
    run_demo_quick_test
    echo ""
    run_log_test
    echo ""
    run_coinm_test
}

# 显示帮助信息
show_help() {
    echo "Binance SDK Unified Examples 运行脚本"
    echo ""
    echo "使用方法:"
    echo "  $0 [example_name]"
    echo ""
    echo "可用的示例:"
    echo "  basic_usage     - 基础使用示例"
    echo "  websocket_usage - WebSocket多产品测试 (Spot/USDM/CoinM) - 真实行情"
    echo "  env_config      - 环境变量配置示例"
    echo "  multi_product   - 多产品类型示例"
    echo "  public_api      - 公共API示例"
    echo "  multi_api_test  - 多产品类型API测试"
    echo "  api_compatibility - API兼容性测试"
    echo "  demo_mode_test  - Demo模式测试"
    echo "  demo_quick_test - Demo模式快速测试"
    echo "  log_test       - 日志测试"
    echo "  coinm_test     - 币本位合约测试"
    echo "  debug_coinm_api - 币本位合约API调试"
    echo "  test_coinm_parsing - 币本位合约解析测试"
    echo "  show_api_keys  - 显示API密钥信息"
    echo "  all            - 运行所有示例"
    echo "  help           - 显示帮助信息"
    echo ""
    echo "环境变量:"
    echo "  BINANCE_API_KEY         - Binance API密钥"
    echo "  BINANCE_SECRET_KEY      - Binance密钥"
    echo "  BINANCE_PRODUCT_TYPE    - 产品类型 (Spot, UsdM, CoinM, Options, Portfolio)"
    echo "  BINANCE_ENVIRONMENT     - 环境 (Demo, Live)"
    echo "  BINANCE_TIMEOUT_SECONDS - 超时时间 (秒)"
    echo "  BINANCE_RETRY_COUNT     - 重试次数"
    echo "  BINANCE_HTTP_PROXY      - HTTP代理 (可选)"
    echo "  BINANCE_WS_PROXY       - WebSocket代理 (可选)"
    echo "  RUST_LOG               - 日志级别 (error, warn, info, debug, trace)"
    echo ""
    echo "示例:"
    echo "  $0 basic_usage"
    echo "  $0 websocket_usage"
    echo "  $0 all"
    echo ""
    echo "设置环境变量后运行:"
    echo "  BINANCE_API_KEY=your_key BINANCE_SECRET_KEY=your_secret $0 basic_usage"
}

# 主函数
main() {
    local example_name=${1:-"help"}
    
    case $example_name in
        "basic_usage")
            check_dependencies
            check_env
            build_project
            run_basic_example
            ;;
        "websocket_usage")
            check_dependencies
            check_env
            build_project
            run_websocket_example
            ;;
        "env_config")
            check_dependencies
            check_env
            build_project
            run_env_config_example
            ;;
        "multi_product")
            check_dependencies
            check_env
            build_project
            run_multi_product_example
            ;;
        "public_api")
            check_dependencies
            check_env
            build_project
            run_public_api_example
            ;;
        "multi_api_test")
            check_dependencies
            check_env
            build_project
            run_multi_api_test
            ;;
        "api_compatibility")
            check_dependencies
            check_env
            build_project
            run_api_compatibility_test
            ;;
        "demo_mode_test")
            check_dependencies
            check_env
            build_project
            run_demo_mode_test
            ;;
        "demo_quick_test")
            check_dependencies
            check_env
            build_project
            run_demo_quick_test
            ;;
        "log_test")
            check_dependencies
            check_env
            build_project
            run_log_test
            ;;
        "coinm_test")
            check_dependencies
            check_env
            build_project
            run_coinm_test
            ;;
        "debug_coinm_api")
            check_dependencies
            check_env
            build_project
            run_debug_coinm_api
            ;;
        "test_coinm_parsing")
            check_dependencies
            check_env
            build_project
            run_test_coinm_parsing
            ;;
        "show_api_keys")
            check_dependencies
            check_env
            build_project
            run_show_api_keys
            ;;
        "all")
            check_dependencies
            check_env
            build_project
            run_all_examples
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            print_error "未知的示例名称: $example_name"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
